import axios from 'axios';
import ip from './../ip';
import store from '../index';
import checkStatus from './checkStatus';
import interceptor from './interceptor';

export default function requestAxios(url,options) {
    const defaultOptions = {
      credentials: 'include',
    };
    const newOptions = { ...defaultOptions, ...options };
    axios.defaults.baseURL = ip+url;
    if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
      if (!(newOptions.body instanceof FormData)) {
        newOptions.headers = {
          Accept: 'application/json',
          'Content-Type': 'application/json; charset=utf-8',
          ...newOptions.headers,
        };
        newOptions.data = JSON.stringify(newOptions.body);
      } else {
        // newOptions.body is FormData
        newOptions.headers = {
          Accept: 'application/json',
          'Content-Type': 'multipart/form-data',
          ...newOptions.headers,
        };
      }
    }

    //  拦截器
    axios.interceptors.request.use((config) => {

      return config;
    },(error) => {
      return Promise.reject(error);
    });
    axios.interceptors.response.use((response) => {
      //  规范返回数据格式
      const returnData = interceptor(response);
      return returnData.data;
    },(error) => {

      return Promise.reject(error);
    });

    const Axios = axios({...newOptions});
    return Axios
      .then(checkStatus)
      .then((response)=>{
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response;
      }
      return response;
    }).catch(e=>{
        const { dispatch } = store;
        const status = e.name;
        if (status === 401) {
          dispatch({
            type: 'login/logout',
          });
          return;
        }
        if (status === 403) {
          //  dispatch(routerRedux.push('/exception/403'));
          return;
        }
        if (status <= 504 && status >= 500) {
          //  dispatch(routerRedux.push('/exception/500'));
          return;
        }
        if (status >= 404 && status < 422) {
          //  dispatch(routerRedux.push('/exception/404'));
        }
     })
}
